﻿using System.Web;
using Telerik.OpenAccess;

namespace SampleWebApplication.Data
{
    public static class DataScope
    {
        public static string SCOPE_KEY = "SCOPE_PROVIDER_KEY";

        public static IObjectScope Create()
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[SCOPE_KEY] == null)
                {
                    IObjectScope scope = DataScopeProvider.GetNewObjectScope();
                    scope.TransactionProperties.AutomaticBegin = true;
                    HttpContext.Current.Items.Add(SCOPE_KEY, scope);
                    return scope;
                }
            }
            return null;
        }

        public static void Dispose()
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[SCOPE_KEY] != null)
                {
                    IObjectScope scope = (IObjectScope)HttpContext.Current.Items[SCOPE_KEY];
                    if (scope.Transaction != null && scope.Transaction.IsActive)
                    {
                        scope.Transaction.Commit();
                    }
                    scope.Dispose();
                }
            }
        }

        public static IObjectScope Get()
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[SCOPE_KEY] != null)
                {
                    return (IObjectScope)HttpContext.Current.Items[SCOPE_KEY];
                }
                else
                {
                    return Create();
                }
            }
            return null;
        }
    }
}
